package com.my.fss.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import redis.clients.jedis.Jedis;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;


@Component
public class FileInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    public Environment env;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果没有expire参数，则快速放行
        if (request.getParameter("expire") == null) {
            return true;
        }

        // 获取文件
        // 先取出rides的key=/oa/2020/0508/刘焕鑫(12).txt?expire=GKmKIh4GUHa
        String uri = request.getRequestURI().substring(4);
        String redisKey = uri + "?" + request.getQueryString();
        String decode = URLDecoder.decode(redisKey, "utf-8");
        // 然后拿key取出{app_id}/oa/2020/0508/刘焕鑫(12).txt
        Jedis jedis = new Jedis(env.getProperty("redis.host"), Integer.parseInt(env.getProperty("redis.port")));
        String value = jedis.get(decode);
        // redis上未发布，直接返回链接超时
        if (StringUtils.isEmpty(value)) {
            response.setStatus(404);
            // response.sendRedirect("404");
            return false;
        }

        // 获取文件保存路径
        String app_id = value.split(":")[0];
        String savePath = value.split(":")[1];
        String save_path = env.getProperty("fss.base.dir") +"/" + app_id + savePath;
        File file = new File(save_path);
        // 判断文件是否存在
        boolean exists = file.exists();
        // 文件不存在直接返回
        if (!exists) {
            response.setStatus(404);
            return false;
        }


        // 文件存在,将文件取出并转为字节流输出
        String fileName = file.getName();
        InputStream in = new FileInputStream(file);
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[1024];
        int n;
        while ((n = in.read(buff)) != -1) {
            outputStream.write(buff, 0, n);
        }
        // 冲刷缓冲区
        outputStream.flush();
        // 关流
        outputStream.close();
        in.close();
        return false;

    }



}
